package com.demo.aviator.service.impl;

import com.demo.aviator.service.IExpress;
import com.demo.aviator.vo.TestAviator;
import com.googlecode.aviator.AviatorEvaluator;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

@Component
public class ExpressImpl implements IExpress {

    @Override
    public String arithmetic() {
        Long result = (Long) AviatorEvaluator.execute("1+2+3");
        return result.toString();
    }

    @Override
    public String logic() {
        Boolean result2 = (Boolean)AviatorEvaluator.execute("3<1 && 2!=4 || true");
        return result2.toString();
    }

    @Override
    public String cpmplex() {
        Map env = new HashMap();
        env.put("yourname","aviator");
        String result3 = (String)AviatorEvaluator.execute(" 'hello ' + yourname ", env);
        return result3;
    }

    @Override
    public String cpmplexExc() {
        String result3 = (String)AviatorEvaluator.exec(" 'hello ' + yourname ", "aviator2");
        return result3;
    }

    @Override
    public String threeExp() {
        String result5=(String)AviatorEvaluator.execute("3>0? 'yes':'no'");
        return result5;
    }

    @Override
    public String callFunction() {
        StringBuilder sb = new StringBuilder();
        sb.append(AviatorEvaluator.execute("string.length('hello')") + " @@ ");    //求字符串长度
        sb.append(AviatorEvaluator.execute("string.contains('hello','h')")+ " @@ ");  //判断字符串是否包含字符串AviatorEvaluator.execute("string.startsWith('hello','h')");  //是否以子串开头AviatorEvaluator.execute("string.endsWith('hello','llo')");是否以子串结尾
        sb.append(AviatorEvaluator.execute("math.pow(-3,2)")+ " @@ ");   //求n次方
        sb.append(AviatorEvaluator.execute("math.sqrt(14.0)")+ " @@ ");   //开 平方根
        sb.append(AviatorEvaluator.execute("math.sin(20)")+ " @@ ");    //正弦函数
        return sb.toString();
    }

    @Override
    public String regular() {
        String email = "satad008@163.com";
        Map<String, Object> env = new HashMap<>();
        env.put("email", email);
        String result = (String) AviatorEvaluator.execute("email=~/([\\w0-8]+@\\w+[\\.\\w+]+)/ ? $1 : 'unkonow' ", env);
        return result;
    }

    @Override
    public String grammar() {
        TestAviator testAviator = new TestAviator();
        testAviator.setName("123");
        testAviator.setAge(0);
        Map<String, Object> env = new HashMap<>();
        env.put("testAviator", testAviator);
        String result = (String) AviatorEvaluator.execute(" 'testAviator.name = ' + testAviator.name ", env);
        return result;
    }

}
